package org.go.smart.temperature;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.go.smart.HouseController;
import org.go.smart.JSONUtil;

@SuppressWarnings("serial")
public class TemperatureServlet extends HttpServlet{

	private HouseController houseController;
	public TemperatureServlet() {
		this.houseController = HouseController.getInstance();
	}

	public void init(ServletConfig config) throws ServletException{
		super.init(config);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();
		
		String[] wantedTemperatures = request.getParameterValues("wantedTemperature");
		String[] rooms = request.getParameterValues("room");
		
		if (wantedTemperatures != null && wantedTemperatures.length > 0 && rooms != null && rooms.length > 0) {
			String wantedTemperature = wantedTemperatures[0];
			String room = rooms[0];
			houseController.getRoomController(room).setWantedTemperature(wantedTemperature);
			
			response.setStatus(HttpServletResponse.SC_OK);
			writer.append("Wanted temperature was successfully set to " + wantedTemperature + " for room: " + room);
		} else {
			response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
			writer.append("Request not understood by server");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		if (request.getParameter("actualTemperatures") != null) {
			writer.append(JSONUtil.buildTemperatures(houseController.getReadTemperatures()));
			response.setStatus(HttpServletResponse.SC_OK);
		} else if (request.getParameter("wantedTemperatures") != null) {
			writer.append(JSONUtil.buildTemperatures(houseController.getWantedTemperatures()));
			response.setStatus(HttpServletResponse.SC_OK);
		} else {
			response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
			writer.append("Request not understood by server");
		}
		writer.write("\r\n");
		writer.close();
	}
}
